<?php
declare(strict_types=1);

namespace Modules\Shop\Service;

use HiCommon\Helper;
use HiCommon\Repository\CouponsRepository;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\EquitiesExtendsRepository;
use HiCommon\Repository\UserInviteSetRepository;
use HiCommon\Repository\EntrustRoleUserRepository;

class CouponService
{

    protected static $status_types = ['1'=>'未使用','2'=>'已使用','3'=>'已过期'];

    /**
	 *	获取优惠券列表
	 *	hinq 2019 08 22
	 *
	 **/
	public function get_list( array $arr_search ){

		//通过当前登录用户的信息获取当前登录用户的角色id
//		$arr_option = ['role_id','user_id'];
//		$arr_map = ['user_id' => shop_user_id() ];


//		$arr_role = EntrustRoleUserRepository::get_one_by_where( (array) $arr_map, (array)$arr_option )->toArray();
//		//如果当前用户的角色在指定的数组内   只获取当前用户自己发布的数据  否则获取全部
//		if( in_array( $arr_role['role_id'] , [3,4]) ){
//			$arr_where['where'] = ['admin_id' => $arr_role['user_id'] ];
//		}



        $arr_where['where'] = ['repairstore_id' => shop_user()['shop_id']];  //获取当前门店下的所有优惠券
        $arr_where['withCount'] = ['count_ling','count_yong','count_guo'];
		$arr_list = CouponsRepository::get_list( (array) $arr_search , (array) $arr_where );

        $coupon_types = ['1'=>'洗车券','2'=>'满减券','3'=>'折扣券'];
        $types = ['1'=>'普通商品','2'=>'服务商品','3'=>'保养套餐'];
		foreach ($arr_list as $key => &$value) {
            $value->pid_msg = $coupon_types[$value->pid];
            $value->type_msg = $types[$value->type];
			$value['discount_num'] = floatval( $value['discount_num'] );
			$value['price'] = floatval( $value['price'] );
			$value['price_all'] = floatval( $value['price_all'] );
		}
		$arr_list->appends($arr_search);//添加链接参数
		$arr_list = list_page_data( $arr_list , $arr_search );
		return hello_success('成功',$arr_list);
	}


	/**
	 *	根据指定的条件查询 2020年75亿  2025年80亿人口
	 *	hinq 2019 08 22
	 *
	 **/
	public function get_where_list( array $arrWhere ){
		return CouponsRepository::get_where_list($arrWhere);
	}

	/**
	 *	验证提交过来的优惠券数据  给岁月以文明 不是给文明以岁月
     *  商户不发放洗车券
	 *	hinq 2019 10 15
	 **/
	public function check_data( array $arrInput ){
		unset( $arrInput['_token'] );
            if( !empty( $arrInput['act'] ) && $arrInput['act'] == 'status' ){
                return $arrInput;
            }
            if( empty( $arrInput['name'] ) ){
                return hello_error('优惠券名称不能为空');
            }
            if( mb_strlen( $arrInput['name'] ) > 20  ){
                return hello_error('优惠券名称不能超过20字符');
            }
            if( empty( $arrInput['pid'] ) ){
                return hello_error('请选择优惠券类型');
            }
            if( !in_array( $arrInput['pid'] , [ 2 ,3 ] ) ){
                return hello_error('优惠券类型错误');
            }
            if( empty( $arrInput['price_all'] ) ){
                return hello_error('请输入最低消费金额');
            }
           	if( $arrInput['pid'] == 1 ){   //洗车券
           		unset( $arrInput['price'] );
           		unset( $arrInput['discount_num'] );
           		unset( $arrInput['price_all'] );
           	}else if( $arrInput['pid'] == 2 ){  //满减券
           		unset( $arrInput['discount_num'] );
           		if( $arrInput['price'] >= $arrInput['price_all'] ){
                	return hello_error('满减金额不能大于等于最低消费金额');
           		}
           	}else if( $arrInput['pid'] == 3 ){	//折扣券
				unset( $arrInput['price'] );
				if( $arrInput['discount_num'] > 100 || $arrInput['discount_num'] < 1 ){
                	return hello_error('折扣数量设置错误');
				}
           	}

           	if( $arrInput['validity_at'] < 1 ){
                return hello_error('有效期设置错误');
           	}
           	return $arrInput;
	}



	/**
	 *	添加优惠券
	 *	hinq 2019 08 22
	 *
	 **/
	public function add_one( array $arrInput ){
		try {
			$temp = self::check_data( (array) $arrInput );
			if( $temp['state'] == 1 ){
                return $temp;
			}
            //添加
            $temp['admin_id'] = shop_user_id();
            $temp['status'] = 1;
            $temp['ticket_num'] = set_coupons_ticket_num( $temp['pid']);
            $res = CouponsRepository::add_one( (array) $temp );
            if (empty($res)) {
                return hello_error('添加失败');
            }
            return hello_success('添加成功');
        } catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }

	}


	/**
	 *	获取指定的优惠券
	 *	hinq 2019 08 22
	 *
	 **/
	public function get_one( int $nId ){
		$arr_info = CouponsRepository::get_one( (int) $nId );
		return $arr_info;
	}


	/**
	 *	编辑优惠券数据
	 * 	hinq 2019 08 22
	 *
	 **/
	public function edit_one( array $arrInput ){
		try {
            //编辑
			$temp = self::check_data( (array) $arrInput );
			if( $temp['state'] == 1 ){
                return $temp;
			}
            //检测当前优惠券是否被人领取，一旦有人领取，禁止该优惠券的修改
            $count = CouponGrantDetailRepository::get_count_by_where( (array) ['coupon_id'=>$arrInput['id']]);
            if( $count > 0 ){
                return hello_error('当前优惠券已被领取，禁止修改任何内容');
            }
           	//如果是修改优惠券的状态  并且是禁用优惠券【检查当前优惠券是否允许被禁用】
           	if( !empty( $temp['status'] ) && $temp['status'] == 2 ){
           		//验证当前优惠券是否设置成权益礼包和分享奖励礼包
           		$where['coupon_id'] = $temp['id'];
           		$count = EquitiesExtendsRepository::get_where_count( (array) $where );  //权益礼包
           		if( $count > 0 ){
                	return ['state'=>2,'msg'=>'该优惠券已被设置未权益礼包，不可禁用','data'=>[],'error'=>''];
           		}

           		$where['id'] = 1;
           		$count = UserInviteSetRepository::get_count_by_where( (array) $where );  //分享奖励礼包
				if( $count > 0 ){
                	return ['state'=>2,'msg'=>'该优惠券已被设置分享奖励礼包，不可禁用','data'=>[],'error'=>''];
           		}

           	}
            if( isset( $temp['act'] ) ){
                unset( $temp['act'] );
            }
            $res = CouponsRepository::edit_one($temp);
            if (empty($res)) {
                return hello_error('编辑失败');
            }
            
            return hello_success('编辑成功', $res);
        } catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}



	/**
	 *	获取优惠券领取、使用情况
	 *	hinq 2019 08 29
	 *
	 **/
	public function get_list_to_use( array $arr_search ){
		$coupon_types = ['1'=>'洗车券','2'=>'满减券','3'=>'折扣券'];
//		$status_types = ['1'=>'未使用','2'=>'已使用','3'=>'已过期'];
		$use_types = ['1'=>'扫码使用 ' , '2'=>'后台搜索券号使用' , '3' => '下单使用优惠券'];
		$arr_ids = [];

		//通过当前登录用户的信息获取当前登录用户的角色id
		$arr_option = ['role_id','user_id'];
		$arr_map = ['user_id' => shop_user_id() ];
		$arr_role = EntrustRoleUserRepository::get_one_by_where( (array) $arr_map, (array)$arr_option )->toArray();
		//如果当前用户的角色在指定的数组内   只获取当前用户自己发布的数据  否则获取全部
		if( in_array( $arr_role['role_id'] , [3,4]) ){
			//获取当前角色下所有的优惠券
			$arr_map['where'] = ['admin_id' => $arr_role['user_id'] , 'status'=>1];
			$arr_map['field'] = ['id'];
			$arr_coupon = CouponsRepository::get_all( (array) $arr_map )->toArray();
			foreach ($arr_coupon as $key => $value) {
				$arr_ids[] = $value['id'];
			}
		}

		$arr_search['arr_ids'] = $arr_ids;
		$arr_where['with'] = ['getUserInfo','getCouponInfo','getShopInfo'];
		$arr_list = CouponGrantDetailRepository::get_list( (array) $arr_search , (array) $arr_where );
		$arr_list->appends($arr_search);//添加链接参数
		$arr_list = list_page_data( $arr_list , $arr_search );
		foreach ($arr_list['data'] as $key => &$value) {
			$value['use_type_msg'] = '';
			if( !empty( $value['use_type'] ) ){
				$value['use_type_msg'] = $use_types[$value['use_type']];
			}
			$value['pid_msg'] = $coupon_types[$value['get_coupon_info']['pid']];
			$value['over_at_msg'] = date('Y-m-d H:i:s' , $value['over_at']);
			$value['status_msg'] = self::$status_types[$value['status']];
		}
		return hello_success('成功',$arr_list);
	}


	/**
     *  使用优惠券 搜索优惠券券号使用
     *  hinq  2019 09 06
     *
     **/
	public function coupon_use( int $nId ){
		try {
			if( empty( $nId ) ){
                return hello_error('参数错误');
			}
			//获取当前数据的详细信息
            $arr_option['field'] = ['id','status','over_at'];
			$arr_info = CouponGrantDetailRepository::get_one( (int) $nId , (array) $arr_option );

			if( $arr_info['status'] == 2 ){
                return hello_error('该优惠券已使用');
			}
			if( $arr_info['status'] == 3 ){
                return hello_error('该优惠券已过期');
			}
			if( $arr_info['over_at'] < time() ){
                return hello_error('该优惠券已过期');
			}
			$arrInput['id'] = $nId;
			$arrInput['use_type'] = 2;   //后台商户手动使用
            $arrInput['status'] = 2;
            $arrInput['repairstore_id'] = shop_shop_id();         //商铺的id
            $arrInput['use_msg'] = '店铺后台操作使用';
            $arrInput['use_time'] = date("Y-m-d H:i:s");  //使用时间
			$res = CouponGrantDetailRepository::edit_one( (array) $arrInput );
            if (empty($res)) {
                return hello_error('使用失败');
            }
            return hello_success('使用成功', $res);
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}




	 /**
     *  优惠券关联用户详情
     *  hinq 2019 09 17
     *
     **/
    public function list_extend( array $arrInput ){
		try{
			$arr_where['with'] = ['getUserInfo','getCouponInfo'];
			if( empty( $arrInput['status'] ) ){
			    $arr_search =['coupon_id'=>$arrInput['id'] ];
			}else{
				$arr_search =['coupon_id'=>$arrInput['id'] , 'status'=>$arrInput['status'] ];
			}
			$arr_list = CouponGrantDetailRepository::get_list_by_where( (array) $arr_search , (array) $arr_where );
			$coupon_types = ['1'=>'洗车券','2'=>'满减券','3'=>'折扣券'];
			foreach ($arr_list as $key => &$value) {
				$value['over_at'] = date("Y-m-d H:i:s",$value['over_at']);
				$value['getCouponInfo']['pid_msg'] = $coupon_types[$value['getCouponInfo']['pid']];
			}
			$arr_list->appends($arrInput);
			$arr_list = list_page_data( $arr_list , $arr_search );
		return hello_success('成功',$arr_list);
		} catch (\Exception $exception) {
	        return ['state'=>1,'msg'=>$exception->getMessage()];
	    }
    }



    /**
     *	获取当前管理员的商户id
     *	hinq 2019 09 25
     *
     **/
    public function get_adminId_to_shopId( array $arr_where ){
    	try{
    		$arr_list = ShopRepository::get_one_by_where( (array) $arr_where , (array)['field'=>['id']]);
    		if( empty( $arr_list->first() ) ){
    			return 0;
    		}else{
    			return $arr_list['id'];
    		}
		} catch (\Exception $exception) {
			return ['state'=>1,'msg'=>$exception->getMessage()];
		}
    }


    /**
     *  商家按照优惠券号搜索优惠券详细信息
     *  hinq 2020 3 14
     *
     **/
    public function get_search_counpon( array $arr_input ){
        try{

            $arr_option['field'] = ['id','user_id','coupon_id','pid','over_at','ticket_num','status'];
            $arr_option['where'] = ['pid'=>1];
            $arr_option['with'] = ['getUserInfo' , 'getCouponInfo'];
            $arr_list = CouponGrantDetailRepository::get_list( (array) $arr_input , (array) $arr_option );

            $arr_list->appends($arr_input);//添加链接参数
            $arr_list = list_page_data( $arr_list , $arr_input );
            foreach ( $arr_list['data'] as $key => &$vo ){
                $vo['over_at'] = date('Y-m-d h:i:s'  , $vo['over_at'] );
                $vo['status_msg'] = self::$status_types[$vo['status']];;
            }
            return hello_success('成功',$arr_list);
        }catch (\Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }



}

